package cn.edu.bit.lixin.blog.action;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import cn.edu.bit.lixin.blog.biz.UserManager;
import cn.edu.bit.lixin.blog.entity.User;
import cn.edu.bit.lixin.blog.util.VerifyCodeUtil;

public class UserAction extends BaseActionSupport {
	private UserManager userManager;
	private String verifyCodeInput;
	private String username;
	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getVerifyCodeInput() {
		return verifyCodeInput;
	}

	public void setVerifyCodeInput(String verifyCodeInput) {
		this.verifyCodeInput = verifyCodeInput;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	/**
	 * 生成验证码
	 */
	public void userVerifyImage(){
		HttpServletResponse response = ServletActionContext.getResponse();
		
		String verifyCode = VerifyCodeUtil.generateVerifyCode();//生成验证码中的字符

		this.setSession("verifyCode", verifyCode);
		//this.setAttribute("verifyCode", verifyCode);
		//System.out.println(this.getSession("verifyCode"));
		BufferedImage image = VerifyCodeUtil.generateVerifyImage(verifyCode);//将生成的字符传入，生成一个验证码图片
		try {
			ImageIO.write(image, "JPG", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 判断输入的验证码是否正确
	 */
	public void checkVerifyCode(){
		HttpServletResponse response = ServletActionContext.getResponse();
		if (!userManager.judgeVerifyCode(verifyCodeInput, (String)this.getSession("verifyCode"))){
			try {
				response.getWriter().print("1"); //1代表验证码不正确
				response.getWriter().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
	}
	
	/**
	 * 判断用户登录是否正确
	 * @return
	 */
	public String checkLogin(){
		this.setAttribute("loginInfo", "");
		User user = userManager.checkLogin(username, password);
		if (user != null){
			this.setSession("loginedUser", user);
			return SUCCESS;
		}
		this.setAttribute("loginInfo", "用户名或密码错误，请重新输入");
		return INPUT;
	}
}
